<?php

namespace App\Http\Controllers\Inspection;

use Exception;
use Illuminate\Http\Request;
use App\Models\Inspection\Circle;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

/**
 * 巡检圈逻辑控制器
 *
 * Date: 23/04/2018
 * @author George
 * @package App\Http\Controllers\Inspection
 */
class CircleController extends Controller
{
	/**
	 * 根据线路获取圈信息集合
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(Request $request)
    {
        $this->validate($request, ['line_id' => 'required']);
        $line_id = $request->get('line_id');
        $paginate = $request->get('paginate');
        $query = Circle::query()->withCount('nodes');
        $query->where('line_id', $line_id);

        if ($paginate) {
            $collection = $query->paginate($paginate);
        } else {
            $collection = $query->get();
        }

        return success($collection);
    }

	/**
	 * 创建圈信息
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function store(Request $request)
    {
        $attributes = $this->validate($request, [
            'project_id' => 'required',
            'line_id' => 'required',
            'name' => 'required',
        ]);

        $attributes['company_id'] = Auth::user()->company_id;
        $circle = Circle::create($attributes);
        return stored($circle);
    }

	/**
	 * 获取详情
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param Circle $circle
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function show(Circle $circle)
    {
    	$circle->nodes = DB::table('circle_node_pivot')->select(['circle_node_pivot.node_id', 'time', 'nodes.name'])->where([
			['line_id', '=', $circle->line_id],
			['circle_id', '=', $circle->id],
		])->leftJoin('nodes', 'circle_node_pivot.node_id', '=', 'nodes.id')->get();
        return success($circle);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Inspection\Circle  $circle
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Circle $circle)
    {
        $attributes = $this->validate($request, [
            'line_id' => 'nullable',
            'name' => 'nullable',
        ]);

        $circle->update($attributes);
        return updated($circle);
    }

    /**
     * Date: 23/04/2018
     * @author George
     * @param Circle $circle
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(Circle $circle)
    {
		try {
			DB::beginTransaction();
			DB::table('circle_node_pivot')->where([
				['line_id', '=', $circle->line_id],
				['circle_id', '=', $circle->id],
			])->delete();
			$circle->delete();
			DB::commit();
			return deleted();
		} catch (Exception $exception) {
			DB::rollBack();
			return internalError('删除圈信息失败');
		}
    }

	/**
	 * 设置巡检点位
	 *
	 * Date: 2018/5/21
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function syncNodes(Request $request)
	{
		$this->validate($request, [
			'line_id' => 'required',
			'circle_id' => 'required',
			'attach' => 'nullable|array',
			'detach' => 'nullable|array',
		]);

		$line_id = $request->get('line_id');
		$circle_id = $request->get('circle_id');
		$attach = $request->get('attach');
		$detach = $request->get('detach', []);

		// 判断是否有数据
		if (count($attach) > 0) {
			foreach ($attach as $item) {
				DB::table('circle_node_pivot')->updateOrInsert([
					'line_id' => $line_id,
					'circle_id' => $circle_id,
					'node_id' => $item['node_id']
				], [
					'line_id' => $line_id,
					'circle_id' => $circle_id,
					'node_id' => $item['node_id'],
					'time' => $item['time']
				]);
			}
		} else {
			// 移除所有数据
			DB::table('circle_node_pivot')->where([
				['line_id', '=', $line_id],
				['circle_id', '=', $circle_id],
			])->delete();
		}

		if (count($detach) > 0) {
			DB::table('circle_node_pivot')->where([
				['line_id', '=', $line_id],
				['circle_id', '=', $circle_id],
			])->whereIn('node_id', $detach)->delete();
		}

		return success([]);
	}
}
